<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item :label="t('candidate.fields.awardsName')" prop="awardsName">
        <el-input
          v-model="queryParams.awardsName"
          :placeholder="t('common.inputTextPlaceholder') + t('candidate.fields.awardsName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-table
      id="iAwardApplication-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('candidate.fields.awardsName')"
        field="awardsName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.awardsType')"
        field="templateName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('candidate.fields.year')"
        field="year"
        align="center"
        show-header-overflow
        show-overflow
        width="80"
      />
      <vxe-column
        :title="t('candidate.fields.status')"
        field="status"
        align="center"
        show-header-overflow
        show-overflow
        width="120"
      >
        <template #default="{ row }">
          <div class="flex justify-center items-center gap-[5px]">
            {{ t(`candidate.applyStatus.${row.status}`) }}
            <el-tooltip v-if="row.status === 6" effect="dark" placement="top">
              <template #content>
                {{ t('candidate.fields.cancelReason') }}: {{ row.cancelReason }}
              </template>
              <el-icon :size="16" color="#ff0000"><WarnTriangleFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('candidate.fields.applyTime')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="300"
      >
        <template #default="{ row }">
          {{ `${formatDate(row.applyStartTime)} ~ ${formatDate(row.applyEndTime)}` }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="150"
      >
        <template #default="{ row }">
          <div class="flex flex-col items-center">
            <!-- 申请 -->
            <el-button
              v-if="row.status === 0 || row.status === -1"
              :disabled="row.applyStartTime > Date.now() || row.applyEndTime < Date.now()"
              link
              type="primary"
              @click="handleApply(row, true)"
            >
              {{ t('candidate.operate.apply') }}
            </el-button>
            <!-- 撤销申请 -->
            <el-button
              v-if="row.status === 1"
              :disabled="row.processStatus !== 0"
              link
              type="primary"
              @click="handleRevokeApply(row)"
            >
              {{ t('candidate.operate.revokeApply') }}
            </el-button>
            <!-- 重新申请，可以延期两天 -->
            <el-button
              v-else-if="row.status === 2"
              :disabled="row.applyEndTime + 2 * 24 * 60 * 60 * 1000 < Date.now()"
              link
              type="primary"
              @click="handleApply(row, true)"
            >
              {{ t('candidate.operate.reapply') }}
            </el-button>
            <!-- 申请详情 -->
            <el-button
              v-if="row.status !== 0 && row.status !== -1"
              link
              type="primary"
              @click="handleApply(row, false)"
            >
              {{ t('candidate.operate.viewApply') }}
            </el-button>
            <el-link
              v-if="row.noticeUrl"
              :href="row.noticeUrl"
              type="primary"
              target="_blank"
              :underline="false"
            >
              {{ t('candidate.operate.view') }}
            </el-link>
            <el-button
              v-if="row.status !== 0 && row.processInstanceId"
              link
              type="primary"
              @click="openProcessInstance(row)"
            >
              {{ t('candidate.operate.auditRecords') }}
            </el-button>
            <el-button v-if="row.status > 2" link type="primary" @click="openDefenseTimeView(row)">
              {{ t('candidate.operate.defenseTime') }}
            </el-button>
          </div>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 申请奖项弹窗 -->
  <ApplicationAwards ref="applicationAwardsRef" @success="getList" />
  <!-- 审批流 -->
  <ProcessInstancePopupView ref="processInstancePopupView" />
  <!-- 答辩安排 -->
  <DefenseTimeView ref="defenseTimeViewRef" />
</template>

<script setup lang="ts">
import { useAppStore } from '@/store/modules/app'
import { formatDate } from '@/utils/formatTime'
import { AwardApplicationApi, AwardVO } from '@/api/awards/candidate'
import type { VxeTableInstance, VxeTablePropTypes } from 'vxe-table'
import ApplicationAwards from '@/views/awards/candidate/ApplicationAwards.vue'
import DefenseTimeView from '@/views/awards/candidate/components/DefenseTimeView.vue'
import ProcessInstancePopupView from '@/views/bpm/processInstance/detail/ProcessInstancePopupView.vue'
import { ElLoading } from 'element-plus'
import { WarnTriangleFilled } from '@element-plus/icons-vue'

/** 奖项 列表 */
defineOptions({ name: 'AwardApplication' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const tableRef = ref<VxeTableInstance>()
const applicationAwardsRef = ref<InstanceType<typeof ApplicationAwards>>()

const loading = ref(true) // 列表的加载中
const list = ref<AwardVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  awardsName: undefined
})
const queryFormRef = ref() // 搜索的表单

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

const handleApply = (row: AwardVO, edit: boolean) => {
  applicationAwardsRef.value?.open(row, edit)
}

// 撤销申请
const handleRevokeApply = async (row: AwardVO) => {
  if (!row.processInstanceId && row.processStatus !== 0) {
    return
  }
  let loading: any = undefined
  try {
    const { value } = await ElMessageBox.prompt(
      t('candidate.revoke.reason'),
      t('candidate.revoke.title'),
      {
        inputValue: '',
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        inputPattern: /^(?!\s*$).+/,
        inputErrorMessage: t('common.inputTextPlaceholder') + t('candidate.revoke.reason')
      }
    )
    if (!value) {
      return
    }
    loading = ElLoading.service({
      lock: true,
      text: t('candidate.revoke.loading'),
      background: 'rgba(0, 0, 0, 0.7)'
    } as any)
    await AwardApplicationApi.revokeApply(row.processInstanceId, value)
    message.success(t('common.success'))
    getList()
  } catch {}
  loading?.close()
}

// 审批流
const processInstancePopupView = ref<InstanceType<typeof ProcessInstancePopupView>>()
const openProcessInstance = (row: AwardVO) => {
  if (!row.processInstanceId) return
  processInstancePopupView.value?.show(row.processInstanceId)
}

// 答辩安排
const defenseTimeViewRef = ref<InstanceType<typeof DefenseTimeView>>()
const openDefenseTimeView = (row: AwardVO) => {
  defenseTimeViewRef.value?.open(row.candidateId)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AwardApplicationApi.getAwardPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style lang="scss" scoped>
:deep(.el-button) {
  & + .el-button {
    margin-left: 0;
  }
}
</style>
